Storing Graphs: List vs. Matrix
The practical application of graph algorithms hinges on how efficiently the structure is stored in memory. We primarily utilize two representation methods, tailored for different graph densities:
-
Adjacency List: An array (indexed by vertex ) where each entry points to a linked list (or dynamic array) containing the neighbors of .
- Benefit: Space efficient for sparse graphs (). Fast iteration over neighbors.
-
Adjacency Matrix: An Boolean array , where if there is an edge , and otherwise.
- Benefit: Extremely fast edge existence lookup. Simple implementation.
Representation Trade-offs
Let and . Understanding the computational trade-offs is crucial for algorithm design.
| Feature | Adjacency List | Adjacency Matrix |
|---|---|---|
| Space Complexity | ||
| Check Edge | ||
| Iterate Neighbors of | ||
| Best Use Case | Sparse Graphs () | Dense Graphs () |
Consider a network graph with vertices and edges. This graph is highly sparse.
1. Which representation minimizes memory usage for this specific graph?
2. What is the time complexity to check if an edge exists using an Adjacency Matrix?
Now, consider a dense social network with 1,000 users where nearly everyone is connected to everyone else ().
3. Which representation's space complexity becomes more acceptable or even preferable?
4. For finding all friends of a user (iterating neighbors) in a sparse graph, why is an Adjacency List faster?